package com.fuang.io.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * bio （使用线程池）
 * 基本逻辑：
 * 1，监听端口
 * 2，接收到一个连接请求
 * 3，从线程池里取一个线程处理连接（读取数据->业务处理->返回请求）
 * Created by Fuang on 2018-9-19.
 */
public class ExecutorTimeServer {

    public static void main(String[] args) {
        int port = 8080;
        ServerSocket server = null;
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        try {
            server = new ServerSocket(port);
            System.out.println("The time server is start in port :" + port);
            Socket socket = null;
            while (true) {
                socket = server.accept(); // 阻塞监听直到有连接建立并获取Socket
                executorService.execute(new TimeServerHandler(socket)); // 新建一个线程处理Socket：read -> handle -> write
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (server != null) {
                System.out.println("The time server close");
                try {
                    server.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                server = null;
            }
        }
    }
}
